<template>
  <view class="donate-container">
    <view class="donate-title">爱心捐赠</view>

    <view class="form-container">
      <!-- 学校选择 -->
      <view class="form-item">
        <view class="form-label">选择学校</view>
        <picker
          @change="handleSchoolChange"
          :range="schoolHouseList"
          range-key="schoolName"
          :value="schoolIndex"
        >
          <view class="picker-value">
            {{ schoolHouseList[schoolIndex]?.schoolName || '请选择学校' }}
          </view>
        </picker>
      </view>

      <!-- 小屋选择 -->
      <view class="form-item">
        <view class="form-label">选择小屋</view>
        <picker
          @change="handleHouseChange"
          :range="currentHouseList"
          range-key="houseName"
          :value="houseIndex"
          :disabled="!schoolHouseList[schoolIndex]?.id"
        >
          <view class="picker-value">
            {{ currentHouseList[houseIndex]?.houseName || '请选择小屋' }}
          </view>
        </picker>
      </view>

      <!-- 捐赠物类型 -->
      <view class="form-item">
        <view class="form-label">物品类型</view>
        <picker
          @change="handleTypeChange"
          :range="typeList"
          range-key="typeName"
          :value="typeIndex"
        >
          <view class="picker-value">
            {{ typeList[typeIndex]?.typeName || '请选择物品类型' }}
          </view>
        </picker>
      </view>

      <!-- 上传图片 -->
      <view class="form-item">
        <view class="form-label">物品图片</view>
        <view class="upload-container">
          <view v-for="(item, index) in imageList" :key="index" class="image-item">
            <image :src="item" mode="aspectFill" class="preview-image" />
            <text class="delete-icon" @tap="deleteImage(index)">×</text>
          </view>

          <view class="upload-button" @tap="chooseImage" v-if="imageList.length < 4">
            <text class="iconfont icon-camera"></text>
            <text>上传图片</text>
          </view>
        </view>
        <text class="upload-tip">最多上传4张图片</text>
      </view>

      <!-- 捐赠物描述 -->
      <view class="form-item">
        <view class="form-label">物品描述</view>
        <textarea
          class="description-input"
          v-model="formData.description"
          placeholder="请描述物品的具体情况，如新旧程度、使用年限等"
        />
      </view>

      <!-- 提交按钮 -->
      <button class="submit-button" @tap="submitForm">提交捐赠申请</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getDonationTypeAPI } from '@/services/home'
import type { DonationType, Donation } from '@/types/home'
import { getSchoolListVoAPI, postDonationAPI } from '@/services/donation'
import type { LoveHouse, SchoolHouse } from '@/types/donation'
import { useMemberStore } from '@/stores/modules/member'

// 获取会员信息
const memberStore = useMemberStore()

// 表单数据（使用Donation类型）
const formData = ref<Donation>({
  lovehouseId: 0,
  categoryId: 0,
  images: '',
  description: '',
})

// 学校和小屋级联数据
const schoolHouseList = ref<SchoolHouse[]>([])
const schoolIndex = ref(0)
const currentHouseList = ref<LoveHouse[]>([]) // 当前选中学校的小屋列表
const houseIndex = ref(0)

// 物品类型
const typeList = ref<DonationType[]>([])
const typeIndex = ref(0)

// 图片列表（存储已上传图片的url）
const imageList = ref<string[]>([])

// 获取学校小屋级联列表
const getSchoolHouseData = async () => {
  try {
    const res = await getSchoolListVoAPI()
    if (res.code === 200 && res.rows && res.rows.length > 0) {
      schoolHouseList.value = res.rows
      // 优先使用memberStore.profile中的schoolId作为默认选中学校
      let defaultSchoolIndex = 0
      if (memberStore.profile?.user?.schoolId) {
        const userSchoolId = memberStore.profile.user.schoolId
        const foundIndex = schoolHouseList.value.findIndex(
          (s: SchoolHouse) => s.id === userSchoolId,
        )
        if (foundIndex !== -1) {
          defaultSchoolIndex = foundIndex
        }
      }
      schoolIndex.value = defaultSchoolIndex
      updateCurrentHouseList()
      // 初始化lovehouseId
      if (
        schoolHouseList.value.length > 0 &&
        schoolHouseList.value[schoolIndex.value].lovehouseList.length > 0
      ) {
        formData.value.lovehouseId = schoolHouseList.value[schoolIndex.value].lovehouseList[0].id
      }
    } else {
      uni.showToast({
        title: '获取学校列表失败',
        icon: 'none',
      })
    }
  } catch (error) {
    uni.showToast({
      title: '获取学校列表失败',
      icon: 'none',
    })
  }
}

// 更新当前选中学校的小屋列表
const updateCurrentHouseList = () => {
  const currentSchool = schoolHouseList.value[schoolIndex.value]
  if (currentSchool && currentSchool.lovehouseList && currentSchool.lovehouseList.length > 0) {
    currentHouseList.value = currentSchool.lovehouseList
    houseIndex.value = 0
    // 初始化lovehouseId
    formData.value.lovehouseId = currentHouseList.value[0].id
  } else {
    currentHouseList.value = []
    houseIndex.value = 0
    formData.value.lovehouseId = 0
    uni.showToast({
      title: '当前学校没有可用的小屋',
      icon: 'none',
    })
  }
}

// 选择学校
const handleSchoolChange = (e: any) => {
  const index = e.detail.value
  schoolIndex.value = index
  updateCurrentHouseList()
}

// 选择小屋
const handleHouseChange = (e: any) => {
  const index = e.detail.value
  houseIndex.value = index
  if (
    currentHouseList.value &&
    currentHouseList.value.length > 0 &&
    currentHouseList.value[index]
  ) {
    formData.value.lovehouseId = currentHouseList.value[index].id
  } else {
    formData.value.lovehouseId = 0
    uni.showToast({
      title: '当前学校没有可用的小屋',
      icon: 'none',
    })
  }
}

// 选择物品类型
const handleTypeChange = (e: any) => {
  const index = e.detail.value
  typeIndex.value = index
  formData.value.categoryId = typeList.value[index].id || 0
}

// 选择图片并立即上传
const chooseImage = () => {
  uni.chooseImage({
    count: 9 - imageList.value.length,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFiles: string[] = res.tempFilePaths as string[]
      tempFiles.forEach((filePath: string) => {
        uni.showLoading({ title: '上传中...' })
        uni.uploadFile({
          url: '/common/upload',
          filePath,
          name: 'file',
          success: (uploadRes) => {
            uni.hideLoading()
            if (uploadRes.statusCode === 200) {
              try {
                const data = JSON.parse(uploadRes.data)
                if (data.code === 200 && data.url) {
                  imageList.value.push(data.url)
                  formData.value.images = imageList.value.join(',')
                } else {
                  uni.showToast({ title: data.msg || '上传失败', icon: 'none' })
                }
              } catch (e) {
                uni.showToast({ title: '上传失败', icon: 'none' })
              }
            } else {
              uni.showToast({ title: '上传失败', icon: 'none' })
            }
          },
          fail: () => {
            uni.hideLoading()
            uni.showToast({ title: '上传失败', icon: 'none' })
          },
        })
      })
    },
  })
}

// 删除图片（按索引删除）
const deleteImage = (index: number) => {
  imageList.value.splice(index, 1)
  formData.value.images = imageList.value.join(',')
}

// 提交表单
const submitForm = async () => {
  // 校验每一项，缺什么提示什么
  if (!formData.value.lovehouseId || formData.value.lovehouseId === 0) {
    uni.showToast({ title: '请选择小屋', icon: 'none' })
    return
  }
  if (!formData.value.categoryId || formData.value.categoryId === 0) {
    uni.showToast({ title: '请选择物品类型', icon: 'none' })
    return
  }
  if (!formData.value.description || formData.value.description.trim() === '') {
    uni.showToast({ title: '请填写物品描述', icon: 'none' })
    return
  }
  if (!imageList.value.length) {
    uni.showToast({ title: '请上传至少一张图片', icon: 'none' })
    return
  }

  uni.showLoading({ title: '提交中...' })

  // 拼接图片url为逗号分隔字符串
  formData.value.images = imageList.value.join(',')

  // TODO: 调用提交表单的API，传递formData.value
  const res = await postDonationAPI(formData.value)
  if (res.code !== 200) {
    uni.showToast({ title: res.msg || '提交失败', icon: 'none' })
    return
  }

  uni.hideLoading()
  uni.showToast({
    title: '捐赠申请提交成功',
    icon: 'success',
  })

  // 只重置图片相关数据和描述，保留学校、小屋、捐赠物类型的选中状态，方便连续捐赠
  formData.value.images = ''
  formData.value.description = ''
  imageList.value = []
}

// 获取物品类型列表
const getDonationTypes = async () => {
  const res = await getDonationTypeAPI()
  typeList.value = res.rows
  // 初始化categoryId
  if (typeList.value.length > 0) {
    typeIndex.value = 0
    formData.value.categoryId = typeList.value[0].id || 0
  }
}

onMounted(() => {
  getDonationTypes()
  getSchoolHouseData()

  // 由于微信小程序环境限制，我们只能尝试添加更多强力的CSS选择器
  // 记录到控制台，作为参考
  console.log('页面已挂载，选择器圆角样式已应用')
})
</script>

<style lang="scss">
.donate-container {
  padding: 30rpx;
  min-height: 100vh;
  background-color: #f2f2f2;

  .donate-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 40rpx;
  }

  .form-container {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .form-item {
      margin-bottom: 30rpx;

      .form-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 15rpx;
        font-weight: 500;
      }

      .picker-value {
        height: 80rpx;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        padding: 0 20rpx;
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #333;
      }

      .description-input {
        background-color: #f8f8f8;
        border-radius: 8rpx;
        padding: 20rpx;
        width: 100%;
        height: 200rpx;
        font-size: 28rpx;
        box-sizing: border-box;
      }

      .upload-container {
        display: flex;
        flex-wrap: wrap;

        .image-item {
          width: 150rpx;
          height: 150rpx;
          margin-right: 20rpx;
          margin-bottom: 20rpx;
          position: relative;

          .preview-image {
            width: 100%;
            height: 100%;
            border-radius: 8rpx;
          }

          .delete-icon {
            position: absolute;
            top: -15rpx;
            right: -15rpx;
            width: 40rpx;
            height: 40rpx;
            background-color: rgba(0, 0, 0, 0.6);
            color: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 30rpx;
            z-index: 1;
          }
        }

        .upload-button {
          width: 150rpx;
          height: 150rpx;
          border: 1px dashed #ccc;
          border-radius: 8rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #999;
          font-size: 24rpx;

          .iconfont {
            font-size: 40rpx;
            margin-bottom: 10rpx;
          }
        }
      }

      .upload-tip {
        font-size: 24rpx;
        color: #999;
        margin-top: 10rpx;
      }
    }

    .submit-button {
      margin-top: 40rpx;
      background: linear-gradient(90deg, #2b85e4, #5cadff);
      color: #fff;
      border-radius: 50rpx;
      height: 90rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      border: none;

      &:disabled {
        background: linear-gradient(90deg, #ccc, #ddd);
        color: #fff;
      }
    }
  }
}
</style>

<style>
/* 全局样式：应用于底部弹出的选择器上方圆角 - 更强力版本 */
.wx-picker,
.uni-picker,
.uni-picker-container .uni-picker,
.uni-select .uni-picker,
.mpvue-picker .mpvue-picker-content,
.picker .picker-modal,
.weui-picker,
.picker-modal,
.picker__mask + .picker__container,
._picker {
  border-radius: 20px 20px 0 0 !important;
  overflow: hidden !important;
}

.wx-picker-header,
.uni-picker-header,
.uni-picker .uni-picker-header,
.mpvue-picker-header,
.picker-header,
.weui-picker__hd,
.picker__container .picker-header,
._picker ._picker__hd {
  border-radius: 20px 20px 0 0 !important;
  border-bottom: 1px solid #eee !important;
  padding: 12px 0 !important;
  background-color: #fff !important;
}

.wx-picker-confirm,
.uni-picker-action-confirm,
.uni-picker .uni-picker-action-confirm,
.mpvue-picker-confirm,
.picker-confirm,
.weui-picker__btn_primary,
.picker__action.confirm,
._picker__btn_primary {
  color: #2b85e4 !important;
  font-weight: 500 !important;
}

.wx-picker-cancel,
.uni-picker-action-cancel,
.uni-picker .uni-picker-action-cancel,
.mpvue-picker-cancel,
.picker-cancel,
.weui-picker__btn_default,
.picker__action.cancel,
._picker__btn_default {
  color: #999 !important;
}

.wx-picker-item-selected,
.uni-picker-item-selected,
.uni-picker .uni-picker-item-selected,
.mpvue-picker .picker-item.picker-selected,
.weui-picker__indicator .weui-select-item,
.picker__list .picker__item_selected,
._picker ._picker__item_selected {
  color: #2b85e4 !important;
  font-weight: 500 !important;
}

.wx-picker-content,
.uni-picker-content,
.uni-picker .uni-picker-content,
.mpvue-picker-content,
.picker-modal-content,
.weui-picker__bd,
.picker__container .picker-content,
._picker ._picker__bd {
  background-color: #fff !important;
}

/* 蒙层样式 */
.wx-mask,
.uni-mask,
.uni-transition-mask,
.mpvue-picker-mask,
.picker-mask,
.weui-mask,
.picker__mask,
._mask {
  background-color: rgba(0, 0, 0, 0.6) !important;
}

/* 微信原生选择器组件样式，通过page标签提高权重 */
page .wx-picker,
page uni-picker .uni-picker-wrapper .uni-picker,
page picker .wx-picker {
  border-top-left-radius: 20px !important;
  border-top-right-radius: 20px !important;
}

/* 全局变量影响，尝试通过:root或page设置 */
:root {
  --picker-radius: 20px;
}

page {
  --picker-header-radius: 20px 20px 0 0;
}

/* 添加内联样式标记，让页面初始化时尝试应用样式 */
.uni-page-head-hd:after {
  content: 'style-applied';
  display: none;
}
</style>
